package com.lancoo.klgcourseware.base;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lancoo.klgcourseware.R;
import com.lancoo.klgcourseware.entity.bean.ErrorStates;
import com.lancoo.klgcourseware.entity.bean.KlgDbConstant;
import com.lancoo.klgcourseware.utils.KlgToolUtils;

/**
 * Created by pengmi on 2019/8/14 11:56
 * Description:
 */
public abstract class BaseKlgActivity extends AppCompatActivity implements View.OnClickListener{

    protected Toolbar mToolbar;
    protected TextView tv_title;
    protected RelativeLayout loadingView,netTipLayout;
    private ImageView img_errorLogo;
    private TextView tv_refreshPage;
    protected long time;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //禁止横屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(getContentViewId());
        setStatusBarColor(this);
        initToolbar();
        //沉浸式
        setViewAndUpdata();

        SharedPreferencesHelper.init(this,"LancooListenClass");
        boolean isHealtheye = SharedPreferencesHelper.getBoolean("stuhealtheye", false);
        if(isHealtheye) {
            openAleterWindow();
        }else{
            closeHealthEye();
        }
    }



    public void initToolbar(){
        mToolbar = findViewById(R.id.toolbar);
        tv_title = findViewById(R.id.toolbar_title);
        tv_title.setText(getTitleName());
        if(mToolbar !=null){
            mToolbar.setTitle("");
            setSupportActionBar(mToolbar);
            mToolbar.setBackgroundResource(R.drawable.klg_shape_top_bg);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setHomeAsUpIndicator(R.mipmap.klg_icon_back);
            setTitleBarPaddingTop();
        }
    }


    public void setTitleBarPaddingTop(){
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT){
            mToolbar.setPadding(mToolbar.getPaddingLeft(), getTopPadding(),0, mToolbar.getPaddingBottom());//-ToolsUtils.dip2px(this,15)
        }
    }
    public int  getTopPadding(){
        return mToolbar.getPaddingTop()+ KlgToolUtils.getStatusHeight(this)-KlgToolUtils.dip2px(this,5);
    }

    /**
     * 设置标题栏、状态栏
     *
     * @param activity
     */
    protected void setStatusBarColor(Activity activity) {
        Window window = activity.getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ViewGroup decorView = (ViewGroup) window.getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            decorView.setSystemUiVisibility(option);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==android.R.id.home){
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    protected abstract int getContentViewId();
    protected abstract String getTitleName();
    protected abstract void setViewAndUpdata();
    protected void reloadData(){}



    /**
     * 加载动画的初始化
     */
    protected void showLoadingProgress(){
        ViewStub viewStub=  findViewById(R.id.viewstub_loading);
        if(viewStub!=null){
            viewStub.inflate();
            loadingView = findViewById(R.id.rl_loading);
        }else {
            loadingView.setVisibility(View.VISIBLE);
        }
        if (netTipLayout != null && netTipLayout.getVisibility() == View.VISIBLE) {
            netTipLayout.setVisibility(View.GONE);
        }
    }


    /**
     * 界面显示异常时的初始化
     */
    protected void showFailureLoad(ErrorStates errorStates){
        if(loadingView!=null){
            loadingView.setVisibility(View.GONE);
        }
        ViewStub stub=  findViewById(R.id.viewstub_error_network);
        if(stub!=null){
            stub.inflate();
            netTipLayout =  findViewById(R.id.rl_error);
            img_errorLogo = findViewById(R.id.img_error_logo);
            tv_refreshPage = findViewById(R.id.tv_refresh_page);
            tv_refreshPage.setOnClickListener(this);
        }else {
            netTipLayout.setVisibility(View.VISIBLE);
        }
        img_errorLogo.setImageResource(errorStates== ErrorStates.DATAERROR?R.mipmap.klg_icon_data_error:R.mipmap.klg_icon_network_error);
        tv_refreshPage.setVisibility(errorStates==ErrorStates.DATAERROR?View.GONE:View.VISIBLE);
    }

    protected void dismissLoadingLayout(){
        if(loadingView!=null){
            loadingView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        int id=v.getId();
        if(id==R.id.tv_refresh_page){
            KlgDbConstant.klg_baseUrl=getSharedPreferences(KlgDbConstant.SP_KNOWLEDGE_COURSE, Context.MODE_PRIVATE).getString(KlgDbConstant.SP_KNOWLEDGE_COURSE_URL, KlgDbConstant.klg_baseUrl);
            netTipLayout.setVisibility(View.GONE);
            reloadData();
        }
    }

    public static boolean requestPermission(Context mContext){
        if (Build.VERSION.SDK_INT < 23) {
            return true;
        }
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
//            Toast.makeText(getApplicationContext(), "没有获取权限,请手动开启权限", Toast.LENGTH_SHORT).show();
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            String[] pressisionArray;
            pressisionArray =new String[]{Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
            ActivityCompat.requestPermissions((Activity) mContext, pressisionArray, 100);//,Manifest.permission.READ_PHONE_STATE
            return false;
        } else {
            return true;
        }
    }

    private FrameLayout frameLayout;
    public void openAleterWindow() {   //打开 dailog 窗口 对 dailog 初始化

        ViewGroup decorView = (ViewGroup) this.getWindow().getDecorView();
        frameLayout = new FrameLayout(getApplicationContext());
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        decorView.addView(frameLayout,params);
        getData();
    }

    public void closeHealthEye()
    {
        ViewGroup decorView = (ViewGroup) this.getWindow().getDecorView();
        decorView.removeView(frameLayout);
    }


    public void getData(){  //获取 存储 sharePrefrence 保存的三原色值
        SharedPreferences preferences=getSharedPreferences("myPreference", Context.MODE_PRIVATE);
        int realFilter = 20;
        int a = (int) (realFilter / 80f * 180);
        int r = (int) (200 - (realFilter / 80f) * 190);
        int g = (int) (180 - ( realFilter / 80f) * 170);
        int b = (int) (60 - realFilter / 80f * 60);
        frameLayout.setBackgroundColor(Color.argb(a, r, g, b));
    }

}
